package com.zf.netty.file;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import org.apache.log4j.Logger;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import javax.swing.*;

public class SwingPane extends JFrame {
    private static final Logger LOGGER = Logger.getLogger(SwingPane.class);
    private static final long serialVersionUID = 1L;
    private JLabel label;
    private Icon icon;
    private String qrContent;
    private static FileServer fileServer;

    public SwingPane() throws HeadlessException {
    }

    public void go() throws Exception {
        // 居中
        setLocationRelativeTo(null);
        JPanel panel = new JPanel(new FlowLayout());
        // 标题
        setTitle(Main.appTitle);
        // 大小
        setSize(300, 400);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        // 文件路径显示
        JLabel filelabel = new JLabel("当前文件：" + new File(Main.fileName).getName());
        filelabel.setToolTipText("当前文件：" + Main.fileName);
        filelabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));//设置鼠标样式

        // 网卡切换
        List<String> ipList = new ArrayList<>();
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (inetAddress.isLoopbackAddress()) {//回路地址，如127.0.0.1
                } else if (inetAddress.isLinkLocalAddress()) {//169.254.x.x
                } else {
                    //非链接和回路真实ip
                    String localip = inetAddress.getHostAddress();
                    ipList.add(localip);
                }
            }
        }
        // 如果有多个网卡,就会涉及IP切换
        JComboBox cmb = new JComboBox();    //创建JComboBox
        if (ipList.size() > 1) {
            cmb.addItem("--多网卡，请选择手机同网段IP--");    //向下拉列表中添加一项
            for (String ip : ipList) {
                cmb.addItem(ip);
            }
        } else {
            cmb.addItem(ipList.get(0));
            refresh(ipList.get(0));
        }

        cmb.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                try {
                    if (e.getStateChange() == ItemEvent.SELECTED) {
                        String ip = e.getItemSelectable().getSelectedObjects()[0].toString();
                        refresh(ip);
                    }
                } catch (Exception ex) {
                    LOGGER.error(ex);
                    System.exit(1);
                }
            }
        });

        // 超链接
        JLabel linklabel = new JLabel(Main.appStartDesc);
        linklabel.setForeground(Color.BLUE);//设置链接颜色
        linklabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));//设置鼠标样式
        linklabel.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {
            }

            @Override
            public void mousePressed(MouseEvent e) {
            }

            @Override
            public void mouseExited(MouseEvent e) {
            }

            @Override
            public void mouseEntered(MouseEvent e) {
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                Desktop desktop = Desktop.getDesktop();
                try {
                    desktop.browse(new URI(Main.appUrl));
                } catch (Exception e1) {
                    LOGGER.error(e1);
                }
            }
        });

        // 二维码
        label = new JLabel();

        setVisible(true);

        panel.add(filelabel);
        panel.add(cmb);
        panel.add(linklabel);
        panel.add(label);

        setContentPane(panel);
    }

    public void refresh(String ip) throws Exception {
        // 简单点，读取空闲的可用端口
        ServerSocket serverSocket = new ServerSocket(0);
        final int port = serverSocket.getLocalPort();
        serverSocket.close();

        // 启动服务
        if(fileServer != null) {
            fileServer.close();
        }
        // 开启一个web服务，用来下载
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    fileServer = new FileServer();
                    fileServer.run(port, Main.fileName);
                } catch (Exception e1) {
                    LOGGER.error(e1);
                    System.exit(1);
                }
            }
        }).start();

        // 更新二维码
        this.qrContent = String.format("http://%s:%s/",ip,port);

        Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix matrix = new MultiFormatWriter().encode(qrContent, BarcodeFormat.QR_CODE, 300, 300, hints);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        icon = new ImageIcon(image);
        label.setIcon(icon);
        label.setHorizontalAlignment(0);
        icon = new ImageIcon(image);
        label.setIcon(icon);
    }
}
